console.log("  background.js");
// web请求监听，最后一个参数表示阻塞式，需单独声明权限：webRequestBlocking
/* chrome.webRequest.onBeforeRequest.addListener(details => {
  console.log(details,"webRequest")
}, {urls: ["<all_urls>"]}, ["blocking"]); */

chrome.commands.onCommand.addListener(function (command) {
  console.log('Command:', command);
});


// 监听来自content-script的消息
chrome.runtime.onMessage.addListener(function (req, sender, back) {
  console.log(req, sender, back, "get from content.js");
  if (req.translate) {
    (async function () {
      $.ajax({
        url: 'http://fanyi.youdao.com/translate',
        method: 'get',
        data: {
          'doctype': 'json',
          type: 'auto',
          i: req.translate
        },
        dataType: 'json',
        success: await function (res) {
          console.log(res, "suc")
          if (res.errorCode == 0) {
            console.log("ssssss", res.translateResult[0][0].tgt, back)
            back(res.translateResult[0][0].tgt)
          } else {
            console.log("res.code不为0")
            back("res.code不为0")
          }
        },
        error(err) {
          console.log(err, "err")
        },
        complete: function (res) {
          console.log(res, "com")
        }
      })
    })();
    return true;
  }
});

//定时判断书签同步
pushOrPull();
(function(){
  setInterval(e=>{
    pushOrPull();
  },60000)
})()
chrome.bookmarks.onCreated.addListener(e=>{
    pushOrPull(true);
    console.log(e,"onCreated")
})
chrome.bookmarks.onRemoved.addListener(e=>{
    pushOrPull(true);
    console.log(e,"onRemoved")
})
chrome.bookmarks.onChanged.addListener(e=>{
    pushOrPull(true);
    console.log(e,"onChanged")
})
chrome.bookmarks.onMoved.addListener(e=>{
    pushOrPull(true);
    console.log(e,"onMoved")
})
chrome.bookmarks.onChildrenReordered.addListener(e=>{
    pushOrPull(true);
    console.log(e,"onChildrenReordered")
})


function  pushOrPull(isSet){
  if(this.lock_listener) return;
  get_bookmarks(e=>{
    if(e){
      $.ajax({
        url:'http://106.52.76.72/chromePlugin/bookmarks',
        method:'post',
        data:{
          data:JSON.stringify(e),
          set:isSet?1:0
        },
        success:e=>{
          if(e.code==0){
            console.log(e.msg)
          }else if (e.code==3){
            console.log(e.msg)
          }else if(e.code==4){
            let bookmarks = JSON.parse(e.data);
            pullBookmarks(bookmarks)
            console.log(e.msg)
          }
        },
        error:e=>{
          console.log(e,"ffffffffff")
        }
      })
    }
  })


/*   $.ajax({
    url:'http://106.52.76.72/chromePlugin/bookmarks',
    method:'get',
    success:e=>{
      console.log(e,"ssssssssss")
      if(e.code==0||e.code==1){

      }
    },
    error:e=>{
      console.log(e,"ffffffffff")
    }
  }) */
}
